package com.hurui.xiaoming.activity.repaymentdetails;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.hurui.xiaoming.R;
import com.hurui.xiaoming.activity.BaseActivity;
import com.hurui.xiaoming.bean.Li_Detail_Result;
import com.hurui.xiaoming.bean.ModifyInfo;
import com.hurui.xiaoming.myconfig.PamaryKeys;
import com.hurui.xiaoming.utils.TimeUtils;
import com.hurui.xiaoming.utils.WriteReadSharedPrefs;
import com.hurui.xiaoming.weight.MoneyTextView;

import java.util.HashMap;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class RepaymentDetailsActivity extends BaseActivity {

    private MoneyTextView money_tv;
    private Map<String, String> map = new HashMap<>();
    private String oi_id;
    private TextView order_info_tv;
    private TextView order_yue_tv;
    private TextView order_time_tv;
    private TextView order_fine_tv;
    private TextView order_status_tv;
    private TextView total_tv;
    private Dialog dialog;
    private TextView order_method;
    private Button order_commit_btn;
    Li_Detail_Result.DataBean data;
    private int method=1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_repayment_details);

        oi_id = getIntent().getStringExtra(PamaryKeys.OI_ID);
        initView();
        initAction();
    }

    @Override
    public void initView() {
        money_tv = (MoneyTextView) findViewById(R.id.money_tv);
        order_info_tv = (TextView) findViewById(R.id.order_info_tv);
        order_yue_tv = (TextView) findViewById(R.id.order_yue_tv);
        order_time_tv = (TextView) findViewById(R.id.order_time_tv);
        order_fine_tv = (TextView) findViewById(R.id.order_fine_tv);
        order_status_tv = (TextView) findViewById(R.id.order_status_tv);
        total_tv = ((TextView) findViewById(R.id.order_total_tv));
        order_method = ((TextView) findViewById(R.id.order_method_tv));
        order_commit_btn = ((Button) findViewById(R.id.order_commit_btn));

        findViewById(R.id.back_iv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onFinish();
            }
        });
        findViewById(R.id.repaymentmethod).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                methodPay(v);
            }
        });

    }

    /**
     * 还款方式
     */
    private void methodPay(View v) {
        View view = LayoutInflater.from(this).inflate(R.layout.pay_method, null);
        final PopupWindow popupWindow=new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable(getResources(),(Bitmap) null));

        popupWindow.setTouchable(true);
        popupWindow.setOutsideTouchable(true);
        view.findViewById(R.id.line_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                order_phone(data);
                order_method.setText("线上还款");
                popupWindow.dismiss();
                setAlpha(1f);
                method=2;


            }
        });
        view.findViewById(R.id.unline_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                order_method.setText("线下还款");
                setAlpha(1f);
                method=1;
                popupWindow.dismiss();
            }
        });
        setAlpha(0.4f);
        popupWindow.showAsDropDown(v);
    }

    private void setAlpha(float bgAlpha){
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getWindow().setAttributes(lp);
    }


    private void myShowDialog() {
        if (dialog==null) {
            dialog = new Dialog(RepaymentDetailsActivity.this);
            dialog.setContentView(LayoutInflater.from(this).inflate(R.layout.paymethod_dialog, null));
        }
        dialog.show();
    }

    @Override
    public void initAction() {
        map.clear();
        map.put(PamaryKeys.OI_ID, oi_id);
        apiSevice.onHTttp_views(map).enqueue(new Callback<Li_Detail_Result>() {
            @Override
            public void onResponse(Call<Li_Detail_Result> call, Response<Li_Detail_Result> response) {

                data = response.body().getData();
                showData(data);
                Log.e("www", "onResponse: "+data.toString() );
            }

            @Override
            public void onFailure(Call<Li_Detail_Result> call, Throwable t) {

            }
        });
        order_commit_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                commitBtn();
            }
        });

    }

    /**
     *
     */
    private void commitBtn() {
        map.clear();
        map.put(PamaryKeys.UI_ID, WriteReadSharedPrefs.readUserID(mContext) + "");
        if (data.getWyprice()!=null){
            map.put("pl_price",data.getHkzje());
        }
        map.put("pl_oiid",data.getOi_id());

        if (data.getNowloans()!=null){
            map.put("pl_loans",data.getNowloans().toString());
        }
        map.put("pl_hktype",method+"");
        apiSevice.onHttp_repay(map).enqueue(new Callback<ModifyInfo>() {
            @Override
            public void onResponse(Call<ModifyInfo> call, Response<ModifyInfo> response) {
                try {
                    String status = response.body().getStatus();
                    if (status!=null)
                    if (status.equals("sucess")){
                        onToast("还款成功");
                    }
                    if (status.equals("repay")){
                        onToast("已经还款");
                    }
                    if (status.equals("error")){
                        onToast("还款失败");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    onToast("还款失败");
                }
            }

            @Override
            public void onFailure(Call<ModifyInfo> call, Throwable t) {

            }
        });
    }

    private void showData(Li_Detail_Result.DataBean data) {
        if (data.getOi_jkprice()!=null&&data.getOi_jkloans()!=null)
        order_info_tv.setText("总借款金额" + data.getOi_jkprice() + "元，分" + data.getOi_jkloans() + "期");
        if (data.getMyyhprice()!=null)
            money_tv.setText(data.getMyyhprice().toString());
        order_yue_tv.setText(data.getNowloans()+"");
        if (data.getHktime()!=null)
        order_time_tv.setText(TimeUtils.getHktime(data.getHktime().toString()));
        if (data.getFxprice()!=null)
        order_fine_tv.setText(data.getFxprice());
        total_tv.setText(data.getHkzje());
        //9审核中/1借款中/2还款中/2还款中/4已逾期/5已结清/6待催收/7已起诉/8不通过
        switch (data.getOi_state()) {
            case "9":
                order_status_tv.setText("审核中");
                break;
            case "1":
                order_status_tv.setText("借款中");
                break;
            case "2":
                order_status_tv.setText("还款中");
                break;
            case "3":
                order_status_tv.setText("已还款");
                break;
            case "4":
                order_status_tv.setText("已逾期");
                break;
            case "5":
                order_status_tv.setText("已结清");
                break;
            case "6":
                order_status_tv.setText("待催收");
                break;
            case "7":
                order_status_tv.setText("已起诉");
                break;
            case "8":
                order_status_tv.setText("不通过");
                break;
        }
    }

    /**
     * 拨打电话
     * @param dataBean
     */
    private void order_phone(final Li_Detail_Result.DataBean dataBean) {

        AlertDialog.Builder localBuilder = new AlertDialog.Builder(mContext);
        localBuilder.setTitle("拨打电话");
        localBuilder.setMessage("+86" + dataBean.getUi_phone());
        /***
         * 设置点击返回键不会消失
         * */
        final AlertDialog dialog = localBuilder.setCancelable(false).create();

        localBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener()
        {
            public void onClick(DialogInterface paramAnonymousDialogInterface, int paramAnonymousInt)
            {
                Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + dataBean.getUi_phone()));
                if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                    return;
                }
                mContext.startActivity(intent);
            }
        });
        localBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener()
        {
            public void onClick(DialogInterface paramAnonymousDialogInterface, int paramAnonymousInt)
            {
                dialog.dismiss();
            }
        });

        localBuilder.show();
    }
}
